import React, { Component } from 'react'
import './App.scss'
import { Header, List, Footer } from './cps'

export default class App extends Component {
  state = {
    todos: [
      {
        id: 0,
        title: '吃饭',
        completed: false
      },
      {
        id: 1,
        title: '睡觉',
        completed: false
      },
      {
        id: 2,
        title: '上号',
        completed: true
      }
    ]
  }
  render() {
    const { todos } = this.state
    return (
      <div className="container">
        <Header click={(todo) => this.addTodos(todo)}></Header>
        <List
          todos={todos}
          change={(id, completed) => this.updateTodos(id, completed)}
          click={(id) => this.deleteTodos(id)}
        ></List>
        <Footer></Footer>
      </div>
    )
  }

  addTodos(todo) {
    // push的返回值，本来就不是数组，是新数组的长度
    this.setState((state) => {
      return {
        todos: state.todos.concat(todo)
      }
    })
  }
  updateTodos(id, completed) {
    this.setState({
      // 根据id获取到指定的对象并修改completed
      todos: this.state.todos.filter((todo) => {
        if (todo.id === id) {
          todo.completed = !completed
        }
        return todo
      })
    })
  }

  deleteTodos(id) {
    // console.log(id)

    // let newTodos = this.state.todos.filter((todo) => {
    //   if (todo.id !== id) {
    //     return todo
    //   }
    // })

    this.setState({
      // 把过滤后的数据组成一个新的数组并覆盖原来的数据达到删除的效果
      todos: this.state.todos.filter((todo) => {
        if (todo.id !== id) {
          return todo
        }
      })
    })
  }
}

// 1. 组件通信应该是单行数据流
// 2. props的数据应该是只读的
